package com.tuling.netty.client;

import com.tuling.netty.client.handler.NettyClientHandler;
import com.tuling.netty.command.LoginCmd;
import com.tuling.netty.handler.CommandDecoder;
import com.tuling.netty.handler.CommandEncoder;
import com.tuling.netty.listener.DefaultNettyListener;
import com.tuling.netty.listener.NettyListener;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class NettyClient {
    private NettyListener listener = new DefaultNettyListener();

    private String inetHost;
    private int inetPort;

    public NettyClient(String inetHost, int inetPort) {
        this.inetHost = inetHost;
        this.inetPort = inetPort;
    }

    public void addListener(NettyListener listener) {
        this.listener = listener;
    }

    public void executeLogin(String doctorId) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new CommandEncoder());
//                        pipeline.addLast(new IdleStateHandler(0, 10, 0, TimeUnit.SECONDS));
                        pipeline.addLast(new CommandDecoder());
                        pipeline.addLast(new NettyClientHandler(NettyClient.this.listener));
                    }
                });

        ChannelFuture channelFuture = bootstrap.connect(inetHost, inetPort);
        channelFuture.addListener((ChannelFutureListener) future -> {
            if (!future.isSuccess()) {
                listener.complete(NettyListener.NettyEvent.CONNECTION_FAILURE);
            } else {
                Channel channel = channelFuture.channel();
                doLogin(doctorId, channel);
                listener.complete(NettyListener.NettyEvent.LOGIN_SUCCESS);
            }
        });
    }

    private void doLogin(String doctorId, Channel channel) {
        LoginCmd login = new LoginCmd();
        login.setDoctorId(doctorId);
        channel.writeAndFlush(login);
    }
}